package main

import (
	"fmt"
	"github.com/aws/aws-sdk-go/aws"
	"time"

	"github.com/aws/aws-sdk-go/aws/session"
	"github.com/aws/aws-sdk-go/service/iotdataplane"
)

func main() {
	// 创建AWS会话
	sess, err := session.NewSessionWithOptions(session.Options{
		Config: aws.Config{
			CredentialsChainVerboseErrors: aws.Bool(true),
			Region:                        aws.String("cn-northwest-1"),
		},
		Profile:           "dev-west",
		SharedConfigState: session.SharedConfigEnable,
	})

	// 创建AWS IoT数据平面服务客户端
	client := iotdataplane.New(sess)

	// 发布消息到IoT主题
	topic := "$aws/things/test/shadow/name/test/get"
	payload := []byte("Hello, AWS IoT!")
	qos := int64(1) // quality of service, 0或1或2，默认为0
	_, err = client.Publish(&iotdataplane.PublishInput{
		Topic:   &topic,
		Payload: payload,
		Qos:     &qos,
	})
	if err != nil {
		panic(err)
	}

	// 订阅IoT主题并接收消息
	subscription := "$aws/things/test/shadow/name/test/get/accepted"
	for {
		resp, err := client.GetThingShadow(&iotdataplane.GetThingShadowInput{
			ThingName: &subscription,
		})
		if err != nil {
			panic(err)
		}

		// 解析消息
		fmt.Println(string(resp.Payload))

		time.Sleep(time.Second)
	}
}
